//
//  ProtocolBase.m
//  Protocol
//
//  Created by  user on 11-1-10.
//  Copyright 2011 GuangZhouXuanWu. All rights reserved.
//

#import "ProtocolBase.h"

#import "ProtocolStream.h"
#import "ProtocolHTTPSREST.h"
//#import "ProtocolBaseDataSecurity.h"

@implementation CProtocolBase

static NSString *s_guid = @"";

//@synthesize m_nEnc;
@synthesize commandID = _nCommandID;
@synthesize nErrorcode = _nErrorcode;
@synthesize szErrormsg = _szErrormsg;
@synthesize transformType = _transformType;

- (id)initWithCommandid:(short)nCommandid
{
    self = [super init];
    //UTF8
    _nStrencoding = 2;
    _btVersion = 0;
    _nCommandID = nCommandid;
    _nErrorcode = 0;
    _szErrormsg = nil;
 //   m_nEnc = 0;
    _transformType = [CProtocolTransformType getTransformType:nCommandid];
    return self;
}

- (void)write:(CProtocolStream *)ps
{
    [ps writeShort:_nStrencoding];
    [ps writeChar:_btVersion/*=(0!=m_nEnc?[self IsNeedEncodeCompressProtocol:m_nCommandID]:m_btVersion)*/];
    [ps writeShort:_nCommandID];
    [ps writeGUID:[[CProtocolBase protocolSessionID] GUIDValue]];
//	if(0!=m_btVersion)
//	{
//		[self WriteEnterprisenumber:ps];
//		[self WriteUsernumber:ps];
//	}

}

- (BOOL)read:(CProtocolStream *)ps
{
//	[ps setPosition:[ps position]+5];
    _nStrencoding = [ps readShort];
    _btVersion = [ps readChar];
    _nCommandID = [ps readShort];

    _nErrorcode = [ps readInt];
    _szErrormsg = [[ps readString] retain_mm];
    return [ps position] < [ps length];
}

- (void)read:(CProtocolStream *)ps output:(NSObject **)obj
{
}


-(void)writeHTTPSREEST:(CProtocolHTTPSREST*)phr
{
    
}

//-(NSDictionary*)readHTTPSREEST:(CProtocolHTTPSREST*)phr
//{
//    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:phr.body options:0 error:nil];
//    _nErrorcode = [[dic valueForKey:@"error_code"] integerValue];
//    _szErrormsg = [[dic valueForKey:@"error_msg"] retain_mm];
//    return (_nErrorcode != 0 || _szErrormsg.length > 0) ? nil : [dic objectForKey:@"response_params"];
//}

-(NSDictionary*)readHTTPSREEST:(CProtocolHTTPSREST*)phr
{
    id *obj = [NSJSONSerialization JSONObjectWithData:phr.body options:0 error:nil];
    
    if([obj isKindOfClass:[NSDictionary class]])
    {
        _nErrorcode = [[obj valueForKey:@"Code"] integerValue];
        _szErrormsg = [[obj valueForKey:@"Message"] retain_mm];
    }
    else
    {
        _nErrorcode = 1;
    }
    

    return (_nErrorcode == 0) ? nil : obj;
}

-(void)readHTTPSREEST:(CProtocolHTTPSREST*)phr output:(NSObject**)obj
{
    
}

+ (void)setProtocolSessionID:(NSString *)guid
{
    ReleaseObj(s_guid);
    s_guid = [[guid lowercaseString] retain_mm];
}

+ (NSString*)protocolSessionID
{
    return s_guid;
}

- (void)dealloc
{
    [_szErrormsg release_mm];
    superdealloc_mm;
}

@end
